<?php

namespace Modules\Manager\Http\Controllers\Admin;
use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\CouponLog;
use App\Models\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Modules\Manager\Entities\Manager;
use Modules\Manager\Helpers\UserData;
use Modules\Manager\Http\Requests\LoginRequest;
use Modules\Manager\Entities\Department;

class LoginController
{
    protected $miniProgram;
    protected $miniProgram2;
    use ResponseData,UserData;
    public function __construct()
    {
        $config = [
            'app_id' => config('wechat.mini_program.manager.app_id'),
            'secret' => config('wechat.mini_program.manager.secret'),
        ];
        $this->miniProgram = Factory::miniProgram($config); // 小程序 - 管理端
        $config2 = [
            'app_id' => config('wechat.mini_program.default.app_id'),
            'secret' => config('wechat.mini_program.default.secret'),
        ];
        $this->miniProgram2 = Factory::miniProgram($config2); // 小程序 - 用户端
    }

//
    public function login(Request $request){
        $session = $this->miniProgram->auth->session($request->code);
        if(isset($session['errcode'])){
            return $this->failed($session['errmsg'],201);
        }
        if(isset($session['session_key'])){
            $user = $this->getUser($session['openid']);
            $res = [
                'session_key'=>$session,
                'message'=>'员工登录请绑定手机号',
            ];
            if($user){
                $res['user'] = $user;
                if(!$user->phone){

                    return $this->failed($res,202);
                }
                if($user->department_id==0||$user->post_id==0){
                    return $this->failed('您已注册成功,请耐心等待管理员分配职务',201);
                }
                $user->session_key=$session;
                $user->token = $this->token($user);
                return $this->success($user);
            }else{
                $data['openid'] = $session['openid'];
                //无主账户
                $account = Manager::query()->create($data);

                return $this->failed($res,202);
            }
        }
    }
    // 用微信code和phone直接登录
    public function loginphone(Department $department,Request $request){
        $session = $this->miniProgram2->auth->session($request->code);
        if(isset($session['errcode'])){
            return $this->failed($session['errmsg'],201);
        }
        if(isset($session['session_key'])){
            $user = Manager::query()->where('phone',$request->phone)->first();
            if($user){
                $departmentdata = $department->find($user->department_id);
                if ($departmentdata) {
                    $user->department_info = $departmentdata;
                }
                $res = [
                    'user'=>$user,
                    'session'=>$session,
                    'token'=>$this->tokenMini($user),
                ];
                return $this->success($res);
            }else{
                return $this->failed("无此用户",201);
            }
        }
    }

    //用户授权登录
    public function binPhone(CouponLog $couponLog,Request $request){
        $user = $this->miniProgram->encryptor->decryptData($request->session_key , $request->iv, $request->encryptedData);
        $data = $this->handleData($user,$request->openid);
        Manager::query()->updateOrCreate(['openid'=>$request->openid],$data);
        return $this->success($data);
    }
    //整理数据
    protected function handleData($userInfo,$openid)
    {
        $data = [
            'username'=>'小程序用户',
            'password'=>encrypt('123456'),
            'phone'=>$userInfo['phoneNumber'],
            //'nickName'=>$userInfo['nickName'],//$data['nickname'],
            //'avatarUrl'=>$userInfo['avatarUrl'],//$data['headimgurl'],
            //'country'=>$userInfo['country'],//$data['headimgurl'],
            //'province'=>$userInfo['province'],//$data['headimgurl'],
            //'city'=>$userInfo['city'],//$data['headimgurl'],
            //'gender'=>$userInfo['gender'],//$data['headimgurl'],
            'openid'=>$openid,
        ];
        if(isset($userInfo['unionId'])){
            $data['unionid']    = $userInfo['unionId'];
        }
        return $data;
    }
    //获取用户身份令牌-不撤销
    protected function tokenMini($user){
        //发布令牌
        return $user->createToken('user_login:'.$user->id)->plainTextToken;

    }
    //获取用户身份令牌
    protected function token($user){
        //撤销用户所有令牌
        $user->tokens()->delete();
        //重新发布令牌
        return $user->createToken('user_login:'.$user->id)->plainTextToken;

    }
    protected function getUser($openid){
        return Manager::query()->where('openid',$openid)->first();
    }
//    账号密码登录
     public function oldLogin(Department $department,LoginRequest $request){
        $user = Manager::query()->where('username', $request->username)->first();
        if (! $user || ! Hash::check($request->password, $user->password)) {
            return $this->failed('账号或者密码错误',201);
        }
        $data['message'] = '登录成功';
       // $user->tokens()->delete();
       $departmentdata = $department->find($user->department_id);
       if ($departmentdata) {
           $user->department_info = $departmentdata;
       }
        $user->token = $user->createToken($request->username)->plainTextToken;
        return $this->success($user,200);
    }
}
